#!/usr/bin/python

import glob
import os
import sys


from PIL import Image

EXTS = 'jpg', 'jpeg', 'JPG', 'JPEG', 'gif', 'GIF', 'png', 'PNG'

def avhash(im):
	if not isinstance(im, Image.Image):
		im = Image.open(im)
	im = im.resize((8, 8), Image.ANTIALIAS).convert('L')
	avg = reduce(lambda x, y: x + y, im.getdata()) / 64.
	return reduce(lambda x, (y, z): x | (z << y),
	  enumerate(map(lambda i: 0 if i < avg else 1, im.getdata())),
	  0)

def hamming(h1, h2):
	h, d = 0, h1 ^ h2
	while d:
		h += 1
		d &= d - 1
	return h

if __name__ == '__main__':
	if len(sys.argv) <= 1:
		print "Usage: %s image1 image2 ..." % sys.argv[0]
	else:
		im = sys.argv[1]
		for filename in sys.argv[1:len(sys.argv)]:
			ext = os.path.splitext(filename)[1].replace(".", "")
			if ext in EXTS:
				h = avhash(filename)
				print "%d\t%s" % (h, os.path.basename(filename))

